/**
 * 首先创建一个 n * n 的二元数组容器，该数组有四条边界：top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1
 * left -> right 方向遍历顶层，res[top][j] = num，num++
 * top -> bottom 方向遍历右层，res[j][right] = num，num++
 * right -> left 方向遍历底层，res[j][right] = num，num++
 * bottom -> top 方向遍历左层，res[j][left] = num，num++
 * @param {number} n
 * @return {number[][]}
 */
const generateMatrix = n => {
  if (n <= 1) return Array(n).fill(0).map(item => new Array(n).fill(n))

  let top = left = 0, bottom = right = n - 1, num = 1
  const res = Array(n).fill(0).map(item => new Array(n).fill(0))

  while (top <= bottom && left <= right) {
    for (let j = left; j <= right; j++) {
      res[top][j] = num
      num += 1
    }
    top += 1
    for (let j = top; j <= bottom; j++) {
      res[j][right] = num
      num += 1
    }
    right -= 1
    for (let j = right; j >= left; j--) {
      res[bottom][j] = num
      num += 1
    }
    bottom -= 1
    for (let j = bottom; j >= top; j--) {
      res[j][left] = num
      num += 1
    }
    left += 1
  }
  return res
}

console.log(generateMatrix(1))